﻿namespace Digitalmes.Application.Mes;

/// <summary>
/// 返工服务
/// </summary>
[ApiExplorerSettings(GroupName = "mes")]
public sealed class QcReworkService : IDynamicWebApiService
{
    private readonly SugarRepository<QcReworkRecord> _reworkRecordRepo;
    private readonly SugarRepository<ProdTransSn> _transSnRepo;
    private readonly SugarRepository<ProdArchive> _archiveRepo;

    public QcReworkService(SugarRepository<QcReworkRecord> reworkRecordRepo, 
        SugarRepository<ProdTransSn> transSnRepo, 
        SugarRepository<ProdArchive> archiveRepo)
    {
        _reworkRecordRepo = reworkRecordRepo;
        _transSnRepo = transSnRepo;
        _archiveRepo = archiveRepo;
    }

    /// <summary>
    /// 查询所有——分页
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<PageResult<QcReworkRecordDto>> GetPagesAsync(QcReworkRecordPageParam param)
    {
        var query = await _reworkRecordRepo.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(param.Sn), m => m.Sn == param.Sn)
            .WhereIF(param.StartTime != null, m => m.RecordTime >= param.StartTime.MinTime())
            .WhereIF(param.EndTime != null, m => m.RecordTime <= param.EndTime.MaxTime())
            .ToPageAsync(param.Page, param.Limit);
        return query.Adapt<PageResult<QcReworkRecordDto>>();
    }

    /// <summary>
    /// 查找 NG 的产品信息
    /// </summary>
    /// <param name="sn">零件码</param>
    /// <returns></returns>
    [HttpGet("{sn}")]
    [AllowAnonymous]
    public async Task<ProdTransSnDto> GetNgAsync(string sn)
    {
        var transSn = await _transSnRepo.GetFirstAsync(m => m.Sn == sn);
        return transSn.Adapt<ProdTransSnDto>();
    }

    /// <summary>
    /// 返工
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [AllowAnonymous]
    public async Task<bool> ReworkAsync(QcReworkRecordParam input)
    {
        var transSn = await _transSnRepo.GetFirstAsync(m => m.Sn == input.Sn);
        if (transSn == null)
        {
            Oops.ThrowBah(ErrCode.E4004);
        }

        if (transSn!.Status != SnStatusEnum.NG)
        {
            Oops.ThrowBah(ErrCode.E4012);
        }

        // 更改 SN 状态
        transSn.Status = SnStatusEnum.OK;
        transSn.ReworkCount++;
        await _transSnRepo.UpdateAsync(transSn, m => new
        {
            m.Status,
            m.ReworkCount,
        });

        // 添加返工记录
        var archive = await _archiveRepo.GetLastAsync(m => m.Sn == input.Sn);
        QcReworkRecord reworkRecord = new()
        {
            Sn = transSn.Sn,
            NgLineId = transSn.CurLineId,
            NgLineCode = transSn.CurLineCode,
            NgOpId = transSn.CurOpId,
            NgOpCode = transSn.CurOpCode,
            NgProcId = transSn.CurProcId,
            NgProcCode = transSn.CurProcCode,
            NgRoutingId = transSn.CurRoutingId,
            NgRoutingCode = transSn.CurRoutingCode,
            Operator = input.Operator,
            Content = input.Content,
            RecordTime = DateTime.Now,
            Version = archive?.Version ?? 0,
        };
        return await _reworkRecordRepo.InsertAsync(reworkRecord);
    }
}
